/**
 * 
 */
package kr.co.insoft.auth.repository.members.impl;

import kr.co.insoft.auth.mapper.mail.MaillingMapper;
import kr.co.insoft.auth.mapper.members.JoinMapper;
import kr.co.insoft.auth.model.members.JoinFormModel;
import kr.co.insoft.auth.repository.members.JoinRepository;
import kr.co.insoft.framework.exceptions.ExceptionCode;
import kr.co.insoft.framework.exceptions.RepositoryException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

/**
 * @author IN-SOFT Inc. GoodwillDD(sylee@in-soft.co.kr)
 * 
 */
@Repository
public class JoinRepositoryImpl implements JoinRepository {

	@Autowired
	JoinMapper joinMapper;

	@Autowired
	MaillingMapper maillingMapper;

	@Override
	public boolean isDuplicateUsername(String username)
			throws RepositoryException {
		try {
			Assert.notNull(username);
		} catch (IllegalArgumentException e) {
			throw new RepositoryException(ExceptionCode.ARGUMENT_ERROR);
		}

		try {
			return joinMapper.isDuplicateUsername(username) > 0;
		} catch (Exception e) {
			throw new RepositoryException(ExceptionCode.REPOSITORY_EXCEPTION, e);
		}
	}

	@Override
	public Long registMember(JoinFormModel joinFormModel)
			throws RepositoryException {
		try {
			Assert.notNull(joinFormModel);
			/* 이외의 Validation은 JoinFormValidator에서 진행한다. */
		} catch (Exception e) {
			throw new RepositoryException(ExceptionCode.ARGUMENT_ERROR);
		}

		try {
			PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
			joinFormModel.setPassword(passwordEncoder.encode(joinFormModel
					.getPassword()));
			return joinMapper.registMember(joinFormModel);
		} catch (Exception e) {
			throw new RepositoryException(ExceptionCode.REPOSITORY_EXCEPTION, e);
		}
	}

	@Override
	public JoinFormModel getUser(Long id) throws RepositoryException {
		try {
			Assert.notNull(id);
		} catch (Exception e) {
			throw new RepositoryException(ExceptionCode.ARGUMENT_ERROR);
		}
		try {
			return joinMapper.getUser(id);
		} catch (Exception e) {
			throw new RepositoryException(ExceptionCode.REPOSITORY_EXCEPTION, e);
		}
	}

	@Override
	public void accountRevitalize(Long id) throws RepositoryException {
		try {
			joinMapper.accountRevitalize(id);
		} catch (Exception e) {
			throw new RepositoryException(ExceptionCode.REPOSITORY_EXCEPTION, e);
		}
	}
}
